package blue.starter.internal.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 1.0 2020-07-24
 */
public class ReflectionUtil
{
	private static Logger logger = LoggerFactory.getLogger(ReflectionUtil.class);

	private ReflectionUtil()
	{
	}

	/**
	 * 从 setter/getter 方法名称取得字段名称
	 *
	 * @param methodName getter/getter 方法名称
	 * @return field 字段
	 */
	public static String field(String methodName)
	{
		String name = null;
		if (methodName.startsWith("is"))
		{
			name = methodName.substring(2);
		}
		else if (methodName.startsWith("set") || methodName.startsWith("get"))
		{
			name = methodName.substring(3);
		}
		if (name == null || name.isEmpty())
			return null;

		return name.substring(0, 1).toLowerCase() + name.substring(1);
	}

	/**
	 * 把对象字段名称转化为表字段名称
	 *
	 * @param field 对象字段名称
	 * @return 表字段名称
	 */
	public static String fieldToColumn(String field)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < field.length(); i++)
		{
			char c = field.charAt(i);
			if (Character.isUpperCase(c))
			{
				if (i > 0)
					sb.append('_');

				sb.append(Character.toLowerCase(c));
			}
			else
			{
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 把表字段名称转化为对象字段名称
	 *
	 * @param column 表字段名称
	 * @return 对象字段名称
	 */
	public static String columnToField(String column)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < column.length(); i++)
		{
			char c = column.charAt(i);
			if (c == '_')
			{
				if (i > 0 && i < column.length() - 1)
				{
					char n = column.charAt(++i);
					sb.append(Character.toUpperCase(n));
				}
			}
			else
			{
				sb.append(c);
			}
		}
		return sb.toString();
	}

}
